<?php


namespace app\api\controller;


use app\common\controller\Api;
use think\Db;

class Token extends Api
{
    protected $noNeedLogin = '*';
    /**
     * 生成token
     * */
    public function create($user_id = null)
    {
        if ($user_id) {
            $token = md5(random_code(36).$user_id);
            $expiretime = strtotime('+72hours'); // 三天过期
            $data = [
                'user_id' =>$user_id,
                'token'=>$token,
                'createtime'=>time(),
                'expiretime'=>$expiretime
            ];
            Db::name('user_token')->where(['user_id'=>$user_id])->delete();
            Db::name('user_token')->insert($data);
            return ['token'=>$token,'expiretime'=>$expiretime];
        }else{
            $this->error('未知错误');
        }
    }
    /**
     * 验证token是否过期
     * */
    public function check()
    {
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token'));

        $info = Db::name('user_token')->where('token',$token)->order('id','desc')->find();
        if (!$info || time()>$info['expiretime'] ) {
            return false;
        } else {
            return true;
        }
    }
}